import { UploaderOptions, UploadFile, UploadStatus, FUploadFileExtend, UploadOutput } from "./type";

/**
 * 对预览数据数据进行排序
 * @param key 
 * @returns 
 */
export function sortPreviewData(key: string) {
    return (x: any, y: any) => {
        // 如果没有这个key属性
        if (!x.hasOwnProperty(key) || x[key] === undefined || x[key] === null) {
            return 1;
        }
        if (!y.hasOwnProperty(key) || y[key] === undefined || y[key] === null) {
            return -1;
        }
        // 如果组件内指定了排序字段
        if (key != 'createTime') {
            let a = "";
            let b = "";
            if (key.indexOf(".") > -1) {
                a = getValue(key, x);
                b = getValue(key, y);
            } else {
                a = x[key];
                b = y[key];
            }
            return a > b ? 1 : -1;
        } else {
            // 日期字段排序
            var oDate1 = new Date(x[key]);
            var oDate2 = new Date(y[key]);
            return oDate1.getTime() > oDate2.getTime() ? -1 : 1;
        }
    };
}
/**
 * 是否判断有类型限制
 * @param allowedContentTypes 
 * @returns 
 */
export function judgeContentTypeLimit(allowedContentTypes: string) {
    let tTypes = allowedContentTypes.split(",");
    let hasAllIndex = tTypes.findIndex((item: string) => {
        return item == "*";
    });
    return hasAllIndex == -1;
}
/**
* 判断是否有文件大小的限制
*/
export function judegeFileSizeLimit(maxFileSize: string | number) {
    return maxFileSize != "0 Byte";
}
/**
 * 格式化
 * @param opts 
 */
export function formatUploadOpts(opts: UploaderOptions, defaultOpts: any) {
    // let defaultOpts = {
    //     // 允许上传的文件类型
    //     allowedContentTypes: "*",
    //     // 默认不限制附件上传个数
    //     maxUploads: 0,
    //     // 单位KB，默认是12M
    //     maxFileSize: "12MB"
    // };
    if (opts) {
        if (opts.hasOwnProperty("allowedContentTypes")) {
            defaultOpts.allowedContentTypes = (opts.allowedContentTypes || []).join(",");
            defaultOpts.allowedContentTypes =
                defaultOpts.allowedContentTypes == "" ? "*" : defaultOpts.allowedContentTypes;
        }
        if (opts.hasOwnProperty("maxUploads")) {
            defaultOpts.maxUploads = opts.maxUploads || 0;
        }
        if (opts.hasOwnProperty("maxFileSize")) {
            defaultOpts.maxFileSize = humanizeBytes(1024 * 1024 * (opts.maxFileSize || 1));
        }
    }
    return defaultOpts;
}


/**
 * 获取文档类型对应的class
 * @param fileName
 */
export function getFileTypeClassName(fileName: string) {
    let clsName = "ffilepreview--filetype";
    // 如果名称为空
    if (!fileName) {
        return clsName + "-any";
    }
    let lastDotIndex = fileName.lastIndexOf(".");
    let fileSuffix = "";
    if (lastDotIndex > -1) {
        fileSuffix = fileName.substring(lastDotIndex + 1).toLocaleLowerCase();
    }
    switch (fileSuffix) {
        case "pdf":
            clsName += "-pdf";
            break;
        case "jpeg":
        case "jpg":
        case "gif":
        case "svg":
        case "png":
        case "bmp":
            clsName += "-img";
            break;
        case "ppt":
        case "pptx":
            clsName += "-ppt";
            break;
        case "doc":
        case "docx":
            clsName += "-doc";
            break;
        case "xls":
        case "xlsx":
            clsName += "-xls";
            break;
        case "txt":
            clsName += "-txt";
            break;
        case "zip":
            clsName += "-zip";
            break;
        case "wps":
            clsName += "-wps";
            break;
        case "wpt":
            clsName += "-wpt";
            break;
        default:
            clsName += "-any";
    }
    return clsName;
}


/**
 * 获取上传进度
 * @param uploadInfo 
 * @returns 
 */
export function getUploadProgress(uploadInfo: UploadOutput) {
    if (uploadInfo["type"] == "done") {
        return 100;
    }
    if (uploadInfo["file"] && uploadInfo["file"]["progress"]) {
        if (uploadInfo["file"]["progress"]["status"] == UploadStatus.Uploading) {
            let tPercentage = uploadInfo["file"]["progress"]["data"]?.["percentage"] || 5;
            return tPercentage > 5 ? tPercentage : 5;
        }
        return 5;
    }
    return 5;
}
/**
 * 获取真实的文件的大小
 */
export function getRealFileSize(fileSize: number | string | undefined) {
    // 如果是字符串
    let tvalue = fileSize;
    if (!fileSize) {
        return "0 Byte";
    }
    if (typeof fileSize == 'string') {
        tvalue = parseInt(fileSize);
    }
    return humanizeBytes(tvalue as number);
}
/**
 * 判断是否能编辑
 * @param fileInfo 
 * @returns 
 */
export function canEditFile(fileInfo: FUploadFileExtend): Boolean {
    if (!fileInfo) {
        return false;
    }
    const editType = [
        "doc",
        "docx",
        "xls",
        "xlsx",
        "ppt",
        "pptx",
        "txt",
        "wps",
        "wpt",
    ];
    const extendName = fileInfo.name
        .substr(fileInfo.name.lastIndexOf(".") + 1)
        .toLowerCase();
    if (extendName) {
        return editType.includes(extendName);
    }

    return false;
}
/**
 * 内部使用
 * 获取值
 * @param field 
 * @param data 
 * @returns 
 */
function getValue(field: string, data: any) {
    if (!data) {
        return "";
    }
    let resultVal = "";
    if (field.indexOf(".") === -1 && data.hasOwnProperty(field)) {
        resultVal = data[field];
    } else {
        resultVal = field.split(".").reduce((obj, key) => {
            if (obj) {
                return obj[key];
            } else {
                return null;
            }
        }, data);
    }
    return resultVal;
}

export function humanizeBytes(bytes: number): string {
    if (bytes === 0) {
        return '0 Byte';
    }

    const k = 1024;
    const sizes: string[] = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
    const i: number = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
const generateId = (): string => {
    return Math.random().toString(36).substring(7);
}
export function makeUploadFile(file: File, index: number): UploadFile {
    return {
        fileIndex: index,
        id: generateId(),
        name: file.name,
        size: file.size,
        type: file.type,
        form: new FormData(),
        progress: {
            status: UploadStatus.Queue,
            data: {
                percentage: 0,
                speed: 0,
                speedHuman: `${humanizeBytes(0)}/s`,
                startTime: null,
                endTime: null,
                eta: null,
                etaHuman: null
            }
        },
        lastModifiedDate: new Date(file.lastModified),
        sub: undefined,
        nativeFile: file
    };
}
export function changeUploadFileToFileExtend(files: UploadFile[]): FUploadFileExtend[] {
    // 如果是数组
    let result: Array<FUploadFileExtend> = [];
    files.forEach(file => {
        let preExtend = { id: '', name: '', size: 0, type: '', extend: null, extendStatus: 0, extendHeaders: null } as FUploadFileExtend;
        for (let resultProp in preExtend) {
            let tempProp = resultProp.replace('extend', 'response');
            if (file.hasOwnProperty(tempProp)) {
                preExtend[resultProp] = file[tempProp];
            }
        }
        result.push(preExtend);
    });

    return result;
}
/**
 * 应用在服务
 * 判断文件大小是否被允许
 */

export function isFileSizeAllowed(maxFileSize: number | undefined, fileSize: number): boolean {
    if (!maxFileSize) {
        return true;
    }
    // fileSize是b单位 maxFileSize是MB单位
    return fileSize <= maxFileSize * 1024 * 1024; // * 8
}
/**
* 判断文件类型是否允许上传
* @param name
*/
export function isContentTypeAllowed(allowedContentTypes: string[], name: string): boolean {
    if (allContentTypesAllowed(allowedContentTypes)) {
        return true;
    }
    // 附件没有后缀
    if (name.lastIndexOf(".") < 0) {
        return false;
    }
    let namesuffix = name.substr(name.lastIndexOf("."));
    // 简化计算
    return (
        allowedContentTypes.findIndex(
            (item) => item.toLowerCase() == namesuffix.toLowerCase()
        ) > -1
    );
}
function allContentTypesAllowed(allowedContentTypes: string[]): boolean {
    return (
        allowedContentTypes.find((type: string) => type === "*") !==
        undefined
    );
}

/**
 * ------------------------------------
 * 提供给默认服务
 * ------------------------------------
 */
/* 
 * @param httpHeaders 
 * @returns 
 */
export function parseResponseHeaders(httpHeaders: string) {
    if (!httpHeaders) {
        return;
    }

    return httpHeaders.split('\n')
        .map((x: string) => x.split(/: */, 2))
        .filter((x: string[]) => x[0])
        .reduce((acc: Object, x: string[]) => {
            acc[x[0]] = x[1];
            return acc;
        }, {});
}
/**
 * 
 * @param sec 
 * @returns 
 */
export function secondsToHuman(sec: number): string {
    return new Date(sec * 1000).toISOString().substr(11, 8);
}